<template>
	<view class="valves-area">
		<text class="valves-header">阀控数量: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  {{getValvesNumber}} 个</text>
		<view class="uni-flex uni-row valves">
			<template v-for="valve in valves">
				<view class="valve-temp">
					<valve class="valve" :name="valve.name"></valve>
				</view>
			</template>
		</view>
		<add-valves
			:show="true"
			:devices="devices"
			v-if="needAddValve"
			@save="save"
			@back="close"
			@close="close"
			@change="change"
			></add-valves>
		<button class="button" type="default" @click="edit">修改</button>
	</view>
</template>

<script>
	import {mapState, mapActions} from 'vuex';
	import addValves from './area/add-valves.vue'
	import valve from './area/valve.vue'
	import xph from '@/common/xph.js'
	export default {
		data() {
			return{
				needAddValve: false,
				// [{
				// 	"id": 16069132,
				// 	"name": "app测试",
				// 	"valves": [{
				// 		"name": "1",
				// 		"num": 0,
				// 		"selected": false
				// 		["groupId": 37]
				// 	}]
				// }]
				devices: [],
				// [{
				// 	"name": "2",
				// 	"facId": 16069132,
				// 	"num": 1,
				// 	"selected": true,
				// 	["groupId": 37]
				// }]
				selectedValve: [],
				// [40,41]
				groupIds: []
			}
		},
		methods:{
			edit(){
				this.needAddValve = true;
				this.$emit('edit')
			},
			close(){
				const that = this;
				uni.showModal({
					title: "还有数据未保存，是否继续退出",
					icon: 'error',
					success (res) {
						if (res.confirm) {
							that.needAddValve = false;
						}
					}
				})
			},
			change(valve){
				valve.selected = !valve.selected
				this.addSelectedValve(valve)
			},
			save(device){
				//查找当前添加的继电器中是否 增加或者修改的继电器
				//检查已选择的继电器里面，每个继电器是否有groupId 选项，或者是否有继电器被取消选择
				let hasChangeValve = !this.selectedValve.every((valve) => {
					if(!!valve.groupId){
						return valve.selected
					}
					return false
				})
				// console.log(this.devices, this.selectedValve);
				if(hasChangeValve){
					//删除继电器
					const currentGroup = this.groups.find(group => {
						return group.id === this.groupIds[0];
					})
					const relayIds = currentGroup.rotationRelays.map(relay => {
						return relay.id;
					})
					const delPromise = relayIds.map(id => xph.deleteRotationRelay(id))
					Promise.all(delPromise).then(res => {
						if(res){
							//添加新加入的继电器
							const selected = this.selectedValve.filter(valve => valve.selected)
							const addPromise = selected.map(valve => xph.setRotationRelay(valve.facId, this.groupIds[0], valve.num))
							Promise.all(addPromise).then(res => {
								if(res){
									console.log(this.selectedValve, hasChangeValve)
									uni.showToast({
										title: "成功"
									})
									this.needAddValve = false;
									//刷新灌溉组信息
									this.setIrrigationInfo(this.user)
								}
							})
						}
					})
				}
				
				
			},
			addSelectedValve(valve){
				// 如果当前选择的继电器中已经包含了该继电器，则设置继电器状态，否则添加进去
				let val = this.selectedValve.find(val => (valve.facId === val.facId && valve.num === val.num))
				if(!val){
					this.selectedValve.push(Object.assign({}, valve))
				}else {
					val.selected = valve.selected
				}
			},
			...mapActions('irrigation', ['setIrrigationInfo']),
		},
		computed:{
			...mapState(['user']),
			...mapState('device', {
				vsdevices: state => state.devices
			}),
			...mapState('irrigation', ['irrigations', 'groups']),
			// [{
			// 	"id": 16069132,
			// 	"name": "app测试",
			// 	"valves": [{
			// 		"name": "1",
			// 		"num": 0,
			// 		"selected": false
			// 	}]
			// }]
			getDevices: {
				get(){
					if(this.vsdevices.length === 0 || this.valves.length === 0 || this.groups.length === 0 || !this.needAddValve){
						return []
					}
					
					// 获取其他区已经选过的设备
					let otherIrrigations = this.irrigations.filter(irri =>{
						return irri.length !== 0 && irri.id !== this.irriId
					})
					// [{
					// 	"facId": 16069132,
					// 	"relay": 1
					// }]
					let otherSelectedValves = [];
					otherIrrigations.map(irri => {
						irri.groups.map(group => {
							group.rotationRelays.map(relay => {
								otherSelectedValves.push({
									facId: relay.facId,
									relay: relay.relay
								})
							})
						})
					})
					
					let devices = this.vsdevices.map(device => {
						//寻找当前设备下， 有哪几个继电器已被选择
						let relays = this.valves.filter(valve => valve.facId === device.id)
						// 寻找当前设备中被选择过的继电器
						let theDeviceOtherSelectValve = otherSelectedValves.filter(valve => valve.facId === device.id)
						// 选在当前设备里面,选择没有被其他灌区选择过的继电器
						let devValves = device.valves.filter(val => !theDeviceOtherSelectValve.find(selv => selv.relay === val.num))

						//寻找所有的继电器，并标注当前组下，哪几个继电器被选择
						let valves = devValves.map(valve => {
							let relay = {
										name: valve.name,
										facId: device.id,
										num: valve.num,
										selected: false
									}
							if(relays.length){
								let val = relays.find(relay => relay.num === valve.num)

								if(val){
									relay.selected = true;
									this.$set(relay, 'groupId', val.groupId)
								}
							}
							return relay;
						})
						return {
							id: device.id,
							name: device.name,
							valves
						}
					})
					return devices;
				}
			},
			getValvesNumber(){
				return this.valves ? this.valves.length : 0;
			}
		},
		props:{
			"irri-id": {
				type: Number,
				required: true
			},
			valves:{
				type: Array,
				required: true,
				validator: (value) => {
					return typeof value === 'object';
				}
			}
		},
		watch:{
			getDevices:{
				handler(val, old){
					this.devices = val
					
					val.map(dev => {
						dev.valves.map(valve => {
							if(valve.selected){
								this.addSelectedValve(valve)
							}
						})
					})
				},
				immediate: true,
				deep: true
			},
			irrigations:{
				handler(val, old){
					const irri = this.irrigations.find(irri =>{
						return irri.id === this.irriId
					})
					if(!!irri){
						this.groupIds = irri.groups.map(group => group.id)
					}
				},
				immediate: true
			}
		},
		components:{
			addValves,
			valve
		}
	}
</script>

<style lang="scss" scoped>
.valves-area{
	padding: 15.29rpx;
	border: 1.17rpx solid #3A615B;
	border-radius: 11.76rpx;
	.valves-header{
		font-size: 35.29rpx;
		font-family: SourceHanSansCN;
		font-weight: 400;
		color: #1D786C;
	}
	.valves{
		justify-content: left;
		flex-wrap: wrap;
		.valve-temp{
			width: 20%;
			margin-top: 25.88rpx;
			.valve{
				// justify-content: center;
				align-items: center;
				// align-self: center;
				.img{
					width: 72.94rpx;
					height: 50.58rpx;
				}
				.text{
					font-size: 21.17rpx;
					font-family: SourceHanSansCN;
					font-weight: 400;
					color: #1D786C;
				}
			}
		}
	}
	.button{
		width: 183.52rpx;
		height: 56.47rpx;
		background: #1D786C;
		border-radius: 11.76rpx;
		margin: 38.82rpx 0 0 auto;
		
		font-size: 35.29rpx;
		font-family: SourceHanSansCN;
		font-weight: 400;
		color: #FFFFFF;
		line-height: 56.47rpx;
	}
}
</style>